class QuestionSystem {
    constructor() {
        this.questions = questionDatabase;
        this.currentQuestionIndex = 0;
        this.currentQuestion = null;
        this.selectedAnswers = [];
        this.userStats = this.loadStats();
        this.favorites = this.loadFavorites();
        this.wrongQuestions = this.loadWrongQuestions();
        this.currentFilter = { category: 'all', subject: null };
        this.filteredQuestions = [...this.questions];
        this.answered = false;
        
        this.init();
    }

    init() {
        this.setupEventListeners();
        this.updateCategoryCounts();
        this.loadQuestion();
        this.updateStats();
    }

    setupEventListeners() {
        // Category filters
        document.querySelectorAll('.category-item').forEach(item => {
            item.addEventListener('click', (e) => {
                this.filterByCategory(e.currentTarget.dataset.category);
            });
        });

        // Subject filters
        document.querySelectorAll('.subject-item').forEach(item => {
            item.addEventListener('click', (e) => {
                this.filterBySubject(e.currentTarget.dataset.subject);
            });
        });

        // Keyboard navigation
        document.addEventListener('keydown', (e) => {
            if (e.key === 'ArrowLeft') this.previousQuestion();
            if (e.key === 'ArrowRight') this.nextQuestion();
            if (e.key === 'Enter') this.submitAnswer();
        });
    }

    filterByCategory(category) {
        // Update active category
        document.querySelectorAll('.category-item').forEach(item => {
            item.classList.remove('active');
        });
        document.querySelector(`[data-category="${category}"]`).classList.add('active');

        this.currentFilter.category = category;
        this.applyFilters();
    }

    filterBySubject(subject) {
        // Toggle subject selection
        const subjectItem = document.querySelector(`[data-subject="${subject}"]`);
        const isActive = subjectItem.classList.contains('active');
        
        document.querySelectorAll('.subject-item').forEach(item => {
            item.classList.remove('active');
        });

        if (!isActive) {
            subjectItem.classList.add('active');
            this.currentFilter.subject = subject;
        } else {
            this.currentFilter.subject = null;
        }

        this.applyFilters();
    }

    applyFilters() {
        this.filteredQuestions = this.questions.filter(q => {
            const categoryMatch = this.currentFilter.category === 'all' || 
                                q.type === this.currentFilter.category;
            const subjectMatch = !this.currentFilter.subject || 
                                q.subject === this.currentFilter.subject;
            return categoryMatch && subjectMatch;
        });

        this.currentQuestionIndex = 0;
        this.loadQuestion();
    }

    updateCategoryCounts() {
        const counts = {
            all: this.questions.length,
            single: this.questions.filter(q => q.type === 'single').length,
            multiple: this.questions.filter(q => q.type === 'multiple').length,
            judge: this.questions.filter(q => q.type === 'judge').length
        };

        Object.keys(counts).forEach(key => {
            const element = document.getElementById(`${key}-count`);
            if (element) element.textContent = counts[key];
        });
    }

    loadQuestion() {
        if (this.filteredQuestions.length === 0) {
            this.showNoQuestions();
            return;
        }

        this.currentQuestion = this.filteredQuestions[this.currentQuestionIndex];
        this.selectedAnswers = [];
        this.answered = false;
        
        this.displayQuestion();
        this.updateNavigationButtons();
        this.hideFeedback();
    }

    showNoQuestions() {
        document.getElementById('question-container').innerHTML = `
            <div class="no-questions">
                <i class="fas fa-search" style="font-size: 3rem; color: #ccc; margin-bottom: 1rem;"></i>
                <h3>没有找到符合条件的题目</h3>
                <p>请尝试选择其他分类或学科</p>
            </div>
        `;
    }

    displayQuestion() {
        const typeMap = {
            'single': '单选题',
            'multiple': '多选题',
            'judge': '判断题'
        };

        // Add question type class to question container for styling
        const questionContainer = document.getElementById('question-container');
        questionContainer.className = `question-container question-type-${this.currentQuestion.type}`;

        document.getElementById('question-type').textContent = typeMap[this.currentQuestion.type];
        document.getElementById('question-number').textContent = 
            `第 ${this.currentQuestionIndex + 1} 题 / 共 ${this.filteredQuestions.length} 题`;
        document.getElementById('question-text').textContent = this.currentQuestion.question;

        this.displayOptions();
        this.updateFavoriteButton();
    }

    displayOptions() {
        const container = document.getElementById('options-container');
        container.innerHTML = '';

        this.currentQuestion.options.forEach((option, index) => {
            const optionElement = document.createElement('div');
            optionElement.className = 'option';
            optionElement.onclick = () => this.selectOption(index);

            const label = this.currentQuestion.type === 'judge' ? 
                (index === 0 ? '✓' : '✗') : 
                String.fromCharCode(65 + index);

            optionElement.innerHTML = `
                <div class="option-label">${label}</div>
                <div class="option-text">${option}</div>
            `;

            container.appendChild(optionElement);
        });
    }

    selectOption(index) {
        if (this.answered) return;

        const options = document.querySelectorAll('.option');
        
        if (this.currentQuestion.type === 'multiple') {
            // Multiple choice: toggle selection, NO instant feedback
            const isSelected = this.selectedAnswers.includes(index);
            if (isSelected) {
                this.selectedAnswers = this.selectedAnswers.filter(i => i !== index);
                options[index].classList.remove('selected');
            } else {
                this.selectedAnswers.push(index);
                options[index].classList.add('selected');
            }
            
            // For multiple choice, only update submit button state
            this.updateSubmitButton();
        } else {
            // Single choice or judge: single selection with immediate feedback
            options.forEach(opt => opt.classList.remove('selected'));
            options[index].classList.add('selected');
            this.selectedAnswers = [index];
            
            // Show immediate feedback for single choice and judge questions
            this.showInstantFeedback();
        }
    }

    showInstantFeedback() {
        if (this.selectedAnswers.length === 0) return;
        
        this.answered = true;
        const isCorrect = this.checkAnswer();
        
        this.showFeedback(isCorrect);
        this.updateUserStats(isCorrect);
        this.highlightAnswers(isCorrect);
        
        // Hide submit button since answer is automatically submitted
        document.getElementById('submit-btn').style.display = 'none';
    }

    updateSubmitButton() {
        const submitBtn = document.getElementById('submit-btn');
        if (this.currentQuestion.type === 'multiple') {
            // For multiple choice, keep submit button visible and enable when selections made
            submitBtn.disabled = this.selectedAnswers.length === 0;
            submitBtn.style.display = 'inline-flex';
            submitBtn.textContent = '提交答案';
        } else {
            // For single choice and judge, hide submit button after selection
            if (this.selectedAnswers.length > 0) {
                submitBtn.style.display = 'none';
            } else {
                submitBtn.style.display = 'inline-flex';
                submitBtn.disabled = true;
                submitBtn.textContent = '提交答案';
            }
        }
    }

    submitAnswer() {
        if (this.selectedAnswers.length === 0 || this.answered) return;

        this.answered = true;
        const isCorrect = this.checkAnswer();
        
        this.showFeedback(isCorrect);
        this.updateUserStats(isCorrect);
        this.highlightAnswers(isCorrect);
        
        document.getElementById('submit-btn').textContent = '已提交';
        document.getElementById('submit-btn').disabled = true;
    }

    checkAnswer() {
        const correct = this.currentQuestion.correctAnswer;
        
        if (this.currentQuestion.type === 'multiple') {
            return Array.isArray(correct) && 
                   this.selectedAnswers.length === correct.length &&
                   this.selectedAnswers.every(ans => correct.includes(ans));
        } else {
            return this.selectedAnswers[0] === correct;
        }
    }

    highlightAnswers(isCorrect) {
        const options = document.querySelectorAll('.option');
        const correctAnswers = Array.isArray(this.currentQuestion.correctAnswer) ? 
            this.currentQuestion.correctAnswer : [this.currentQuestion.correctAnswer];

        options.forEach((option, index) => {
            option.classList.remove('selected');
            
            if (correctAnswers.includes(index)) {
                option.classList.add('correct-answer');
            }
            
            if (this.selectedAnswers.includes(index)) {
                if (correctAnswers.includes(index)) {
                    option.classList.add('correct');
                } else {
                    option.classList.add('wrong');
                }
            }
        });
    }

    showFeedback(isCorrect) {
        const feedback = document.getElementById('answer-feedback');
        const result = document.getElementById('feedback-result');
        const explanation = document.getElementById('feedback-explanation');

        feedback.className = `answer-feedback ${isCorrect ? 'correct' : 'wrong'}`;
        result.className = `feedback-result ${isCorrect ? 'correct' : 'wrong'}`;
        
        result.innerHTML = isCorrect ? 
            '<i class="fas fa-check-circle"></i> 回答正确！' : 
            '<i class="fas fa-times-circle"></i> 回答错误！';
        
        // Show correct answer instead of explanation
        const correctAnswerText = this.getCorrectAnswerText();
        explanation.innerHTML = `<strong>正确答案：</strong>${correctAnswerText}`;
        
        feedback.style.display = 'block';
    }

    getCorrectAnswerText() {
        const question = this.currentQuestion;
        let correctText = '';
        
        if (question.type === 'judge') {
            // For true/false questions
            correctText = question.options[question.correctAnswer];
        } else if (question.type === 'multiple') {
            // For multiple choice questions
            const correctOptions = question.correctAnswer.map(index => {
                const label = String.fromCharCode(65 + index);
                return `${label}. ${question.options[index]}`;
            });
            correctText = correctOptions.join('、');
        } else {
            // For single choice questions
            const label = String.fromCharCode(65 + question.correctAnswer);
            correctText = `${label}. ${question.options[question.correctAnswer]}`;
        }
        
        return correctText;
    }

    hideFeedback() {
        document.getElementById('answer-feedback').style.display = 'none';
        document.getElementById('submit-btn').textContent = '提交答案';
        document.getElementById('submit-btn').disabled = false;
        document.getElementById('submit-btn').style.display = 'inline-flex';
    }

    updateUserStats(isCorrect) {
        const questionId = this.currentQuestion.id;
        
        if (!this.userStats.answered.includes(questionId)) {
            this.userStats.answered.push(questionId);
        }

        if (isCorrect) {
            if (!this.userStats.correct.includes(questionId)) {
                this.userStats.correct.push(questionId);
            }
            // Remove from wrong answers if previously wrong
            this.userStats.wrong = this.userStats.wrong.filter(id => id !== questionId);
            this.wrongQuestions = this.wrongQuestions.filter(id => id !== questionId);
        } else {
            if (!this.userStats.wrong.includes(questionId)) {
                this.userStats.wrong.push(questionId);
                this.wrongQuestions.push(questionId);
            }
            // Remove from correct answers if previously correct
            this.userStats.correct = this.userStats.correct.filter(id => id !== questionId);
        }

        this.saveStats();
        this.saveWrongQuestions();
        this.updateStats();
    }

    previousQuestion() {
        if (this.currentQuestionIndex > 0) {
            this.currentQuestionIndex--;
            this.loadQuestion();
        }
    }

    nextQuestion() {
        if (this.currentQuestionIndex < this.filteredQuestions.length - 1) {
            this.currentQuestionIndex++;
            this.loadQuestion();
        }
    }

    updateNavigationButtons() {
        document.getElementById('prev-btn').disabled = this.currentQuestionIndex === 0;
        document.getElementById('next-btn').disabled = 
            this.currentQuestionIndex === this.filteredQuestions.length - 1;
    }

    toggleFavorite() {
        const questionId = this.currentQuestion.id;
        const btn = document.getElementById('favorite-btn');
        
        if (this.favorites.includes(questionId)) {
            this.favorites = this.favorites.filter(id => id !== questionId);
            btn.classList.remove('active');
            btn.innerHTML = '<i class="far fa-heart"></i>';
        } else {
            this.favorites.push(questionId);
            btn.classList.add('active');
            btn.innerHTML = '<i class="fas fa-heart"></i>';
        }
        
        this.saveFavorites();
    }

    updateFavoriteButton() {
        const btn = document.getElementById('favorite-btn');
        const isFavorite = this.favorites.includes(this.currentQuestion.id);
        
        if (isFavorite) {
            btn.classList.add('active');
            btn.innerHTML = '<i class="fas fa-heart"></i>';
        } else {
            btn.classList.remove('active');
            btn.innerHTML = '<i class="far fa-heart"></i>';
        }
    }

    updateStats() {
        document.getElementById('total-answered').textContent = this.userStats.answered.length;
        document.getElementById('correct-count').textContent = this.userStats.correct.length;
        document.getElementById('wrong-count').textContent = this.userStats.wrong.length;
        
        const accuracy = this.userStats.answered.length > 0 ? 
            Math.round((this.userStats.correct.length / this.userStats.answered.length) * 100) : 0;
        document.getElementById('accuracy-rate').textContent = accuracy + '%';
    }

    showStats() {
        this.hideAllPanels();
        document.getElementById('stats-panel').style.display = 'block';
        this.renderSubjectProgress();
    }

    showFavorites() {
        this.hideAllPanels();
        document.getElementById('favorites-panel').style.display = 'block';
        this.renderFavorites();
    }

    showWrongQuestions() {
        this.hideAllPanels();
        document.getElementById('wrong-panel').style.display = 'block';
        this.renderWrongQuestions();
    }

    hideAllPanels() {
        document.getElementById('question-container').style.display = 'none';
        document.getElementById('stats-panel').style.display = 'none';
        document.getElementById('favorites-panel').style.display = 'none';
        document.getElementById('wrong-panel').style.display = 'none';
    }

    showQuestions() {
        this.hideAllPanels();
        document.getElementById('question-container').style.display = 'block';
    }

    renderSubjectProgress() {
        const subjects = ['math', 'chinese', 'english', 'science'];
        const subjectNames = {
            'math': '数学',
            'chinese': '语文', 
            'english': '英语',
            'science': '科学'
        };
        
        const container = document.getElementById('subject-progress');
        container.innerHTML = '';

        subjects.forEach(subject => {
            const subjectQuestions = this.questions.filter(q => q.subject === subject);
            const answeredCount = subjectQuestions.filter(q => 
                this.userStats.answered.includes(q.id)).length;
            const progress = subjectQuestions.length > 0 ? 
                (answeredCount / subjectQuestions.length) * 100 : 0;

            const progressItem = document.createElement('div');
            progressItem.className = 'progress-item';
            progressItem.innerHTML = `
                <span>${subjectNames[subject]}</span>
                <div class="progress-bar">
                    <div class="progress-fill" style="width: ${progress}%"></div>
                </div>
                <span>${answeredCount}/${subjectQuestions.length}</span>
            `;
            container.appendChild(progressItem);
        });
    }

    renderFavorites() {
        const container = document.getElementById('favorites-list');
        const favoriteQuestions = this.questions.filter(q => this.favorites.includes(q.id));
        
        if (favoriteQuestions.length === 0) {
            container.innerHTML = '<p>还没有收藏任何题目</p>';
            return;
        }

        container.innerHTML = '';
        favoriteQuestions.forEach(question => {
            const item = this.createQuestionItem(question);
            container.appendChild(item);
        });
    }

    renderWrongQuestions() {
        const container = document.getElementById('wrong-list');
        const wrongQuestionsList = this.questions.filter(q => this.wrongQuestions.includes(q.id));
        
        if (wrongQuestionsList.length === 0) {
            container.innerHTML = '<p>太棒了！还没有答错的题目</p>';
            return;
        }

        container.innerHTML = '';
        wrongQuestionsList.forEach(question => {
            const item = this.createQuestionItem(question);
            container.appendChild(item);
        });
    }

    createQuestionItem(question) {
        const typeMap = {
            'single': '单选题',
            'multiple': '多选题', 
            'judge': '判断题'
        };

        const item = document.createElement('div');
        item.className = 'question-item';
        item.onclick = () => this.goToQuestion(question.id);
        
        item.innerHTML = `
            <div class="question-item-header">
                <span class="question-item-type">${typeMap[question.type]}</span>
            </div>
            <div class="question-item-text">${question.question}</div>
        `;
        
        return item;
    }

    goToQuestion(questionId) {
        const questionIndex = this.filteredQuestions.findIndex(q => q.id === questionId);
        if (questionIndex !== -1) {
            this.currentQuestionIndex = questionIndex;
            this.showQuestions();
            this.loadQuestion();
        }
    }

    // Data persistence
    loadStats() {
        const saved = localStorage.getItem('questionStats');
        return saved ? JSON.parse(saved) : {
            answered: [],
            correct: [],
            wrong: []
        };
    }

    saveStats() {
        localStorage.setItem('questionStats', JSON.stringify(this.userStats));
    }

    loadFavorites() {
        const saved = localStorage.getItem('favorites');
        return saved ? JSON.parse(saved) : [];
    }

    saveFavorites() {
        localStorage.setItem('favorites', JSON.stringify(this.favorites));
    }

    loadWrongQuestions() {
        const saved = localStorage.getItem('wrongQuestions');
        return saved ? JSON.parse(saved) : [];
    }

    saveWrongQuestions() {
        localStorage.setItem('wrongQuestions', JSON.stringify(this.wrongQuestions));
    }

    // Clear functions
    clearFavorites() {
        if (this.favorites.length === 0) {
            alert('收藏列表已经是空的');
            return;
        }
        
        if (confirm('确定要清空所有收藏的题目吗？此操作不可撤销。')) {
            this.favorites = [];
            this.saveFavorites();
            this.renderFavorites();
            this.updateFavoriteButton();
            alert('收藏列表已清空');
        }
    }

    clearWrongQuestions() {
        if (this.wrongQuestions.length === 0) {
            alert('错题本已经是空的');
            return;
        }
        
        if (confirm('确定要清空错题本吗？此操作不可撤销。')) {
            this.wrongQuestions = [];
            this.userStats.wrong = [];
            this.saveWrongQuestions();
            this.saveStats();
            this.renderWrongQuestions();
            this.updateStats();
            alert('错题本已清空');
        }
    }
}

// Global functions
let questionSystem;

function showStats() {
    questionSystem.showStats();
}

function showFavorites() {
    questionSystem.showFavorites();
}

function showWrongQuestions() {
    questionSystem.showWrongQuestions();
}

function previousQuestion() {
    questionSystem.previousQuestion();
}

function nextQuestion() {
    questionSystem.nextQuestion();
}

function submitAnswer() {
    questionSystem.submitAnswer();
}

function toggleFavorite() {
    questionSystem.toggleFavorite();
}

function clearFavorites() {
    questionSystem.clearFavorites();
}

function clearWrongQuestions() {
    questionSystem.clearWrongQuestions();
}

function toggleMobileMenu() {
    const sidebar = document.querySelector('.sidebar');
    sidebar.classList.toggle('mobile-open');
}

// Initialize the system
document.addEventListener('DOMContentLoaded', () => {
    questionSystem = new QuestionSystem();
    
    // Add click handler to logo to return to questions
    document.querySelector('.logo').addEventListener('click', () => {
        questionSystem.showQuestions();
    });
});